<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.kcinit_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{type,size,row,index}" slot="menuBtn">
        <el-dropdown-item divided @click.native="importCourse(row)">导入排课</el-dropdown-item>
      </template>
    </avue-crud>

    <el-dialog title="排课导入"
               append-to-body
               :visible.sync="excelBox"
               v-if="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter" :upload-before="uploadBefore" :upload-error="uploadError">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate()">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, add, update, remove, enableOrDisableCoursePlanInit} from "@/api/service/drpkgl";
import {mapGetters} from "vuex";
// import {getToken} from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            search: true,
            rules: [{
              required: true,
              message: "请输入学校名称",
              trigger: "blur"
            }],
            type: "tree",
            cascader: ['xqId'],
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            props: {
              label: "xxName",
              value: "id"
            },
            // value: '3',
            // defaultValue:'3'
          },
          {
            label: "排课名称",
            span: 12,
            prop: "initName",
            // search: true,
            rules: [{
              required: true,
              message: "请输入课程名称",
              trigger: "blur"
            }],
            maxlength: 100,
            showWordLimit: true
          },
          {
            label: "学期",
            prop: "xqName",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [{
              required: true,
              message: "请输入学期",
              trigger: "blur"
            }],

          },
          {
            label: "学期",
            prop: "xqId",
            search: false,
            rules: [{
              required: true,
              message: "请选择学期",
              trigger: "blur"
            }],
            hide: true,
            type: "select",
            dicUrl: "/api/ManageClassCoursePlan/GetSchoolSemesterSelect?schoolId={{key}}",
            props: {
              label: "xqName",
              value: "id"
            },
          },
          {
            label: "周上课天数",
            prop: "kcts",
            rules: [{
              required: true,
              message: "请输入周课时数",
              trigger: "blur"
            }],
            type: "number",
          },
          {
            label: "上午课程数",
            prop: "swjs",
            rules: [{
              required: true,
              message: "请输入上午课程数",
              trigger: "blur"
            }],
            type: "number",
          },
          {
            label: "下午课程数",
            prop: "xwjs",
            rules: [{
              required: true,
              message: "请输入下午课程数",
              trigger: "blur"
            }],
            type: "number",
          },
          {
            label: "晚上课程数",
            prop: "wsjs",
            rules: [{
              required: true,
              message: "请输入晚上课程数",
              trigger: "blur"
            }],
            type: "number",
          },
          {
            label: "是否启用排课设置",
            prop: "status",
            rules: [{
              required: true,
              message: "请选择诉求类型",
              trigger: "blur"
            }],
            type: "tree",
            dicData: [
              {
                label: "禁用",
                value: 0
              },
              {
                label: "启用",
                value: 1
              }
            ],
            nodeClick: (data, node) => {
              console.log("学生,", node)
              this.statusTypeChange()

            },
          },
        ]
      },
      data: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "第一步: 请点击下面的按钮下载Excel模板，并按照模板填写信息",
            labelWidth: 426,
            type: 'title',
            prop: "title",
            span: 24,
            styles: {
              // color: 'red',
              fontSize: '24px'
            }
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
          {
            formslot: true,
            label: "第二步: 导入Excel模板文件",
            labelWidth: 200,
            type: 'title',
            prop: "title1",
            span: 24,
            styles: {
              // color: 'red',
              fontSize: '24px'
            }
          },
          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '导入数据处理需要时间，请耐心等待！',
            accept: ".xls,.xlsx",
            span: 24,
            // propsHttp: {
            //   res: 'data'
            // },
            data: {id: ''},
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/ManageClassCoursePlan/ImportCoursePlan",
          },

        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.kcinit_add, false),
        viewBtn: this.vaildData(this.permission.kcinit_view, false),
        delBtn: this.vaildData(this.permission.kcinit_delete, false),
        editBtn: this.vaildData(this.permission.kcinit_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    statusTypeChange() {
      let params = {
        id: this.form.id
      }
      enableOrDisableCoursePlanInit(params).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
      });
    },
    // 导入排课
    importCourse(row) {
      console.log(row)
      let excelFile = this.findObject(this.excelOption.column, "excelFile");
      excelFile.data.id = row.id
      this.excelForm = {}
      this.excelBox = true
    },
    rowSave(row, done, loading) {
      row.id = row.id === '' ? '0' : row.id
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      console.log('searchChange', params)
      let newParams = {schoolId: params.schoolId}
      this.query = newParams;
      this.page.currentPage = 1;
      this.onLoad(this.page, newParams);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.schoolId = (params.schoolId === undefined || params.schoolId === null) ? '0' : params.schoolId
      console.log('params.schoolId', params)
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      // const school = this.findObject(this.option.column, "schoolId");
      // school.value = "3"
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      done();
      this.$message({
        type: "success",
        message: "导入成功!"
      });
      this.excelBox = false;
    },
    uploadBefore(file, done, loading, column) {
      console.log('1111111111111',file, column)
      this.$confirm("确定要导入排课吗？如果之前已经排了课，将会删除之前的数据！", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        done()
      }).catch(()=>{
        // done();
        this.excelBox = false;
      })
    },
    uploadError(){
      this.$message({
        type: "error",
        message: "导入排课失败，请稍后重试!"
      });
    },
    handleTemplate() {
      // https://ossdata.kaibujiaoyu.com/images/202309011647040827.xlsx
      // window.open('https://ossdata.kaibujiaoyu.com/images/202309011647040827.xlsx');
      window.open('https://kaibupri.oss-cn-wulanchabu.aliyuncs.com/template/ClassScheduleTemplate.xlsx');
    },
  }
};
</script>

<style>
</style>
